package com.lagou.utils;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.sql.SQLException;

/**
 * @program: spring_transfer
 * @description:
 * @author: Mr.Wang
 * @create: 2020-12-16 10:30
 **/
@Component("transManage")
@Aspect
public class TransManage {
	@Autowired
	private ConnectionUtils connectionUtils;

	@Around("execution(* com.lagou.service.impl.AccountServiceImpl.*(..))")
	public Object around(ProceedingJoinPoint pjp){
		Object o = null;

		try {
			beginTransaction();
			o = pjp.proceed();
			commit();
		} catch (Throwable e) {
			e.printStackTrace();
			rollback();
		} finally {
			close();
		}
		return o;
	}

	public void beginTransaction(){
		try {
			connectionUtils.getConnection().setAutoCommit(false);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void commit(){
		try {
			connectionUtils.getConnection().commit();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void rollback(){
		try {
			connectionUtils.getConnection().rollback();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void close(){
		try {
			connectionUtils.getConnection().setAutoCommit(true);
			connectionUtils.getConnection().close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		connectionUtils.removeConnection();

	}
}
